/**
 * 客户管理
 *
 * */
$(function () {
    window.$loading = $('.com-loading');
    var config = {
        coloum_num: 8, //列数目
        query: '/clientele/query?',
        'delete': '/clientele/delete',
        allow: '/clientele/update'
    };
    var query = {}, sort_ = {};
    //查询按钮
    var $searchBar = $('.search-btn');
    //条件input框
    var $search = $('.search');

    $searchBar.click(function () {
        $(this).button('loading');
        //查询方法
        search({keyword: $search.val()});
    });

    function search(obj) {
        var query_ = {};
        $.extend(query_, query, obj instanceof Object ? obj : {});
        $loading.fadeIn();
        var arg = [];
        if (!_.isEmpty(query_) && JSON.stringify(query_) == JSON.stringify(query)) { //查询条件和上次一样，取消请求
            $searchBar.button('reset');
            return $loading.fadeOut();
        }
        query = query_;
        query.timestamp = Date.now();
        Object.keys(query_).map(function (key) {
            if (query_[key]) {
                arg.push(key + '=' + query_[key])
            }
        });

        $.get(config.query + arg.join('&'), function (res) {
            $searchBar.button('reset');
            if (res.list.length) {
                render(res.list, res)
            } else {
                render(noData(config.coloum_num));
                $('.reset-query').click(function () {
                    $search.val('');
                    $searchBar.click();
                })
            }
            var page = res.page;
            pageInit(page,query,search);
            $loading.fadeOut();
        });
    }

    $('[name=status]').change(function () {
        search({status: $(this).val()})
    });
    //页面加载执行
    search();


    $('.table th .fa').click(function (e) {
        var sort = {sortField: '', sortOrder: ''};

        sort.sortField = $(this).data('sort');
        sort_ = sort;
        if ($(this).hasClass('fa-sort') || $(this).hasClass('fa-sort-desc')) {
            sort.sortOrder = 'ASC';
            $(this)
                .removeClass('fa-sort-desc fa-sort')
                .addClass('fa-sort-asc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort');
        } else if ($(this).hasClass('fa-sort-asc')) { //asc
            sort.sortOrder = 'DESC';
            $(this)
                .removeClass('fa-sort-asc fa-sort')
                .addClass('fa-sort-desc');
            $(this)
                .closest('th')
                .siblings('th')
                .find('.fa')
                .removeClass('fa-sort-desc fa-sort-asc')
                .addClass('fa-sort')
        }
        search(sort);
    });
    function shouldCombine() {
        return ((query.sortField == 'com_name') || (query.sortField == 'unit_code'))
    }

    function render(list, res) {
        $('.table-responsive .table tbody').html('');

        var group_list = {};
        if (shouldCombine()) {
            console.log('query');

            var list_ = list.map(function (item, index) {
                return {sort: item.comName + item.unitCode, ids: item.id};
            });
            group_list = _.groupBy(list_, "sort");
            for (var rp in group_list) {
                group_list[rp] = _.sortBy(_.pluck(group_list[rp], "ids")).toString()
            }
        }
        if (list instanceof Array) {
            list.forEach(function (item, index) {
                if (shouldCombine()) {
                    var key = item.comName + item.unitCode;
                    var isFirst = false, rowSpan = 1;

                    if ((',' + group_list[key] + ',').indexOf(',' + item.id + ',') == 0) {
                        isFirst = true;
                        rowSpan = group_list[key].split(',').length
                    }
                    $('.table-responsive .table tbody')
                        .append('<tr> \
                    <td scope="row">' + (index + 1) + ' \
                </td> \
                ' + (isFirst ? ('<td ' + (isFirst ? ('style="height:' + 34 * rowSpan + 'px;padding:0 8px;line-height:' + 34 * rowSpan + 'px"') : '') + ' rowspan="' + (isFirst ? rowSpan : '1') + '">' + item.comName + '</td>') : '') + ' \
                ' + (isFirst ? ('<td ' + (isFirst ? ('style="height:' + 34 * rowSpan + 'px;padding:0 8px;line-height:' + 34 * rowSpan + 'px"') : '') + ' rowspan="' + (isFirst ? rowSpan : '1') + '">' + item.unitCode + '</td>') : '') + ' \
                <td>' + item.person + '</td> \
                <td>' + item.phone + '</td> \
                <td>' + (item.status == '-1' ? '未申请' : (item.status == '0' ? '<span class="label label-danger">未审核</span>' : (item.status == '1' ? '审核通过' : (item.status == '2' ? '审核未通过' : '')))) + '</td> \
                <td>' + (item.status == '2' ? (item.reason || '-') : '') + '</td> \
                <td>' + item.tel + '</td> \
                <td>' + item.fax + '</td> \
                <td>' + formatDate(item.createAt) + '</td> \
            <td class="text-right" style="width: 232px;"> \
                <div class="btn-group" role="group" aria-label="..." style="width: 204px;padding:1px 5px;"> \
                <a href="./detail.html?id=' + item.id + '">查看</a><a href="./set-detail.html?id=' + item.id + '" class="btn btn-xs btn-primary ">设置经营范围</a>' +
                            (item.status == '0' ? '<a href="javascript:void(0);" data-id="' + item.id + '" class="btn btn-xs btn-success ">通过</a><a href="javascript:void(0);" data-id="' + item.id + '" class="btn btn-xs btn-danger ">拒绝</a>' : '') +
                            '</div> \
                            </td> \
                            </tr>')

                } else {
                    $('.table-responsive .table tbody')
                        .append('<tr> \
                    <td scope="row">' + (index + 1) + ' \
                </td> \
                <td>' + item.comName + '</td> \
                <td>' + item.unitCode + '</td> \
                <td>' + item.person + '</td> \
                <td>' + item.phone + '</td> \
                <td>' + (item.status == '-1' ? '未申请' : (item.status == '0' ? '<span class="label label-danger">未审核</span>' : (item.status == '1' ? '审核通过' : (item.status == '2' ? '审核未通过' : '')))) + '</td> \
                <td>' + (item.status == '2' ? (item.reason || '-') : '') + '</td> \
                <td>' + item.tel + '</td> \
                <td>' + item.fax + '</td> \
                <td>' + formatDate(item.createAt) + '</td> \
                <td>' + item.businessCard + '</td> \
                <td>' + item.attach + '</td> \
                <td>' + item.address + '</td> \
                <td>' + (item.paperBank||'') + '</td> \
                <td>' + (item.paperAccount||'') + '</td> \
                <td>' + (item.paperTel||'') + '</td> \
                <td>' + item.unitCode + '</td> \
            <td class="text-right" style="width: 232px;padding:1px 5px;"> \
                <div class="btn-group" role="group"  \
                style="width: 204px;"> \
                <a href="./detail.html?id=' + item.id + '">查看</a><a href="./set-detail.html?id=' + item.id + '" class="btn btn-xs btn-primary ">设置经营范围</a>' +
                            (item.status == '0' ? '<a href="javascript:void(0);" data-id="' + item.id + '" class="btn btn-xs btn-success ">通过</a><a href="javascript:void(0);" data-id="' + item.id + '" class="btn btn-xs btn-danger ">拒绝</a>' : '') +
                            '</div> \
                            </td> \
                            </tr>')
                }
            });
            // <a href="./clientele-add.html?id=' + item.id + '" class="btn btn-xs danger btn-default interactive opt-update" >修改 \
            // </a>
            $('.btn-success').click(function () {
                var self = this;
                var $id = $(this).data('id');
                if (confirm('确认审核通过？')) {
                    $.post(config.allow, {id: $id, status: 1}, function (xhr, data) {
                        if (xhr.code == 200) {
                            alert("审核成功!");
                            search({timestamp:Date.now()});
                        } else {
                            alert(xhr.error);
                        }
                    });
                }
            });
            $('.btn-danger').click(function () {
                var $id = $(this).data('id');
                var self = this;
                var reason = prompt("请输入原因：", "");
                if (reason != null && reason != "") {
                    $.post(config.allow, {id: $id, status: 2, reason: reason}, function (xhr, data) {
                        if (xhr.code == 200) {
                            alert("审核更新成功!");
                            search({timestamp:Date.now()});
                        } else {
                            alert(xhr.error);
                        }
                    });
                }
            });
        } else {
            $('.table-responsive .table tbody').html(list);
        }
    }
})